﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Xml;

namespace OF.Utility
{
    public class SendSmsHelper
    {
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="smsParam">参数对象</param>
        /// <param name="msg">错误信息</param>
        /// <returns></returns>
        public static bool SendMsg(SmsParam param, out string msg)
        {
            string noteContent = System.Web.HttpUtility.UrlEncode(param.Content);
            string targetUrl = param.SmsUrl;
            targetUrl += "/MongateSendSubmit?userId=" + param.Account + "&password=" + param.PassWord + "&pszMobis=" + param.Mobile + "&pszMsg=" + noteContent + "&iMobiCount=1&pszSubPort=*&MsgId=1789";

            return HttpGet(targetUrl, out msg);
        }

        /// <summary>
        /// 发送短信(服务)
        /// </summary>
        /// <param name="smsParam">参数对象，如果是多个手机号，请用逗号隔开</param>
        /// <param name="msg">错误信息</param>
        /// <returns></returns>
        public static bool SendServiceMsg(SmsParam smsParam, out string msg)
        {
            string targetUrl = smsParam.SmsUrl;
            string noteContent = System.Web.HttpUtility.UrlEncode(smsParam.Content);
            string[] mobileArray = smsParam.Mobile.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            targetUrl += "/MongateSendSubmit?userId=" + smsParam.Account + "&password=" + smsParam.PassWord + "&pszMobis=" + smsParam.Mobile + "&pszMsg=" + noteContent + "&iMobiCount=" + mobileArray.Length + "&pszSubPort=*&MsgId=1789";

            Encoding myEncoding = Encoding.GetEncoding("gb2312");
            string param =
                HttpUtility.UrlEncode("userId", myEncoding) +
                "=" + HttpUtility.UrlEncode(smsParam.Account, myEncoding) +
                "&" + HttpUtility.UrlEncode("password", myEncoding) +
                "=" + HttpUtility.UrlEncode(smsParam.PassWord, myEncoding) +
                "&" + HttpUtility.UrlEncode("pszMobis", myEncoding) +
                "=" + HttpUtility.UrlEncode(smsParam.Mobile, myEncoding) +
                "&" + HttpUtility.UrlEncode("pszMsg", myEncoding) +
                "=" + HttpUtility.UrlEncode(noteContent, myEncoding) +
                "&" + HttpUtility.UrlEncode("iMobiCount", myEncoding) +
                "=" + HttpUtility.UrlEncode(mobileArray.Length.ToString(), myEncoding) +
                "&" + HttpUtility.UrlEncode("pszSubPort", myEncoding) +
                "=" + HttpUtility.UrlEncode("*", myEncoding) +
                "&" + HttpUtility.UrlEncode("MsgId", myEncoding) +
                "=" + HttpUtility.UrlEncode("1789", myEncoding);
            return HttpGet(targetUrl, out msg);


        }

        /// <summary>
        /// 发送短信(服务)
        /// </summary>
        /// <param name="smsParam">参数对象，如果是多个手机号，请用逗号隔开</param>
        /// <param name="msg">错误信息</param>
        /// <returns></returns>
        public static bool SendServiceMsgPost(SmsParam smsParam, out string msg)
        {
            try
            {
                string targetUrl = smsParam.SmsUrl;

                string noteContent = System.Web.HttpUtility.UrlEncode(smsParam.Content);
                string[] mobileArray = smsParam.Mobile.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                targetUrl += "/MongateSendSubmit";
                string param = "?userId=" + smsParam.Account + "&password=" + smsParam.PassWord + "&pszMobis=" + smsParam.Mobile + "&pszMsg=" +
                               noteContent + "&iMobiCount=" + mobileArray.Length + "&pszSubPort=*&MsgId=1789";

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUrl);

                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Accept = "*/*";
                request.Headers.Add("Accept-Encoding: gzip,deflate");
                request.Headers.Add("Accept-Language: zh-cn");

                byte[] bytes = Encoding.UTF8.GetBytes(param);
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();

                var response = request.GetResponse();
                using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    string resultStr = reader.ReadToEnd();

                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(resultStr);
                    //XmlNode msgNode = xmlDoc.SelectSingleNode("string");
                    msg = xmlDoc?.InnerText ?? "";
                    if (msg.Length <= 15)
                    {
                        //发送失败 log
                        return false;
                    }
                    return true;
                }
            }
            catch (Exception e)
            {
                msg = "发送短信失败，接口连接失败，请联系管理员";
                return false;
            }
        }

        /// <summary>
        /// GET Method  
        /// </summary>
        /// <param name="targetUrl"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        private static bool HttpGet(string targetUrl,out string msg)
        {
            var request = WebRequest.Create(targetUrl) as HttpWebRequest;
            if (request != null)
            {
                request.Method = "GET";

                //获取服务器返回的资源  
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                    {
                        string resultStr = reader.ReadToEnd();

                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.LoadXml(resultStr);
                        //XmlNode msgNode = xmlDoc.SelectSingleNode("string");
                        msg = xmlDoc?.InnerText ?? "";
                        if (msg.Length <= 15)
                        {
                            //发送失败 log
                            return false;
                        }
                        return true;
                    }
                }
            }
            else
            {
                msg = "发送短信失败，接口连接失败，请联系管理员";
                return false;
            }
        }

    }

    public class SmsParam
    {
        /// <summary>
        /// 接口地址
        /// </summary>
        public string SmsUrl
        {
            get;set;
        }

        /// <summary>
        /// 账号
        /// </summary>
        public string Account
        {
            get;set;
        }

        /// <summary>
        /// 密码
        /// </summary>
        public string PassWord
        {
            get;set;
        }

        /// <summary>
        /// 手机号
        /// </summary>
        public string Mobile
        {
            get;set;
        }

        /// <summary>
        /// 发送内容
        /// </summary>
        public string Content
        {
            get;set;
        }
    }
}
